package com.echo.service;

import com.echo.dao.CommentDao;
import com.echo.entity.Comment;
import com.echo.exception.CommentException;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.echo.dao.UserDao;
import com.echo.entity.User;

/**
 * 评论服务层：处理评论相关的业务逻辑
 */
public class CommentService {
    private static final Logger logger = Logger.getLogger(CommentService.class.getName());
    private final CommentDao commentDao;
    
    // 分页参数常量
    public static final int PAGE_SIZE = 5; // 每页显示5条评论
    
    /**
     * 默认构造方法，初始化CommentDao
     */
    public CommentService() {
        this.commentDao = new CommentDao();
    }
    
    /**
     * 添加新评论
     * @param articleId 文章ID
     * @param userId 用户ID
     * @param content 评论内容
     * @param parentId 父评论ID（可为null）
     * @return 添加的评论ID
     * @throws CommentException 评论相关异常
     */
    public int addComment(Integer articleId, Integer userId, String content, Integer parentId) throws CommentException {
        logger.info("添加评论: articleId=" + articleId + ", userId=" + userId + ", parentId=" + parentId);
        System.out.println("===== 开始添加评论 =====");
        System.out.println("评论参数: articleId=" + articleId + ", userId=" + userId + ", parentId=" + parentId);
        
        // 参数校验
        System.out.println("开始参数校验");
        validateCommentParams(articleId, userId, content);
        System.out.println("参数校验通过");
        
        // 创建评论对象
        System.out.println("创建评论对象");
        Comment comment = new Comment();
        comment.setArticleId(articleId);
        comment.setUserId(userId);
        comment.setContent(content.trim());
        comment.setParentId(parentId);
        
        Date now = new Date();
        comment.setCreateTime(now);
        comment.setIsDeleted(0);
        
        try {
            // 保存评论并获取自动生成的ID
            System.out.println("调用commentDao.insert()保存评论");
            int commentId = commentDao.insert(comment);
            System.out.println("评论保存成功，生成的评论ID: " + commentId);
            
            logger.info("评论添加成功，ID: " + commentId);
            // 返回自动生成的评论ID
            return commentId;
        } catch (SQLException e) {
            System.out.println("添加评论时发生数据库异常: " + e.getMessage());
            e.printStackTrace();
            logger.log(Level.SEVERE, "添加评论时发生数据库异常: " + e.getMessage(), e);
            throw new CommentException("添加评论失败，请稍后重试", e);
        }
    }
    
    /**
     * 根据文章ID获取评论分页数据
     * @param articleId 文章ID
     * @param currentPage 当前页码
     * @return 包含评论列表、分页信息的Map
     * @throws CommentException 评论相关异常
     */
    public Map<String, Object> getCommentsByArticleId(Integer articleId, Integer currentPage) throws CommentException {
        logger.info("获取文章评论: articleId=" + articleId + ", page=" + currentPage);
        System.out.println("===== CommentService.getCommentsByArticleId开始 =====");
        System.out.println("参数: articleId=" + articleId + ", currentPage=" + currentPage);
        
        // 参数校验
        if (articleId == null || articleId <= 0) {
            throw new CommentException("无效的文章ID");
        }
        
        if (currentPage == null || currentPage <= 0) {
            currentPage = 1; // 默认第一页
        }
        
        try {
            // 获取评论总数
            System.out.println("开始查询评论总数...");
            int totalComments = commentDao.countByArticleId(articleId);
            System.out.println("评论总数查询完成: totalComments=" + totalComments);
            
            // 计算总页数
            int totalPages = (totalComments + PAGE_SIZE - 1) / PAGE_SIZE;
            System.out.println("计算总页数: totalPages=" + totalPages);
            
            // 确保当前页码不超过总页数
            if (currentPage > totalPages && totalPages > 0) {
                currentPage = totalPages;
                System.out.println("调整当前页码: currentPage=" + currentPage);
            }
            
            // 获取评论列表
            System.out.println("开始查询评论列表...");
            List<Comment> comments = commentDao.findByArticleId(articleId, currentPage, PAGE_SIZE);
            System.out.println("评论列表查询完成: comments.size()=" + comments.size());
            
            // 打印评论详情
            for (int i = 0; i < comments.size(); i++) {
                Comment c = comments.get(i);
                System.out.println("评论[" + i + "]: id=" + c.getId() + ", userId=" + c.getUserId() + ", content=" + c.getContent());
            }
            
            // 为每条评论加载其回复（支持嵌套回复）
            System.out.println("开始加载回复...");
            for (Comment comment : comments) {
                System.out.println("  加载评论ID=" + comment.getId() + "的回复...");
                List<Comment> replies = loadRepliesRecursively(comment.getId());
                System.out.println("  回复数: " + replies.size());
                comment.setReplies(replies);
            }
            
            // 构建返回结果
            System.out.println("开始构建返回结果...");
            Map<String, Object> result = new HashMap<>();
            result.put("comments", comments);
            result.put("currentPage", currentPage);
            result.put("totalPages", totalPages);
            result.put("totalComments", totalComments);
            result.put("pageSize", PAGE_SIZE);
            
            // 是否有上一页和下一页
            result.put("hasPrevious", currentPage > 1);
            result.put("hasNext", currentPage < totalPages);
            
            System.out.println("返回结果: comments.size()=" + comments.size() + ", totalComments=" + totalComments + ", totalPages=" + totalPages);
            logger.info("获取评论完成: 共" + totalComments + "条，第" + currentPage + "/" + totalPages + "页");
            System.out.println("===== CommentService.getCommentsByArticleId结束 =====");
            return result;
            
        } catch (SQLException e) {
            System.out.println("获取评论时发生数据库异常: " + e.getMessage());
            e.printStackTrace();
            logger.log(Level.SEVERE, "获取评论时发生数据库异常: " + e.getMessage(), e);
            throw new CommentException("获取评论失败，请稍后重试", e);
        }
    }
    
    /**
     * 删除评论（物理删除）
     * @param commentId 评论ID
     * @param userId 操作用户ID
     * @return 是否删除成功
     * @throws CommentException 评论相关异常
     */
    public boolean deleteComment(Integer commentId, Integer userId) throws CommentException {
        logger.info("删除评论: commentId=" + commentId + ", userId=" + userId);
        
        // 参数校验
        if (commentId == null || commentId <= 0) {
            throw new CommentException("无效的评论ID");
        }
        
        if (userId == null || userId <= 0) {
            throw new CommentException("请先登录");
        }
        
        try {
            // 检查用户角色和评论所有权
            UserDao userDao = new UserDao();
            User user = userDao.findById(userId);
            
            if (user == null) {
                throw new CommentException("用户不存在");
            }
            
            boolean isAdmin = user.getRole() == 1; // 1表示管理员
            
            if (!isAdmin) {
                // 非管理员只能删除自己的评论
                // 查询评论信息，检查是否属于当前用户
                Comment comment = commentDao.findById(commentId);
                if (comment == null || comment.getUserId() != userId) {
                    throw new CommentException("无权删除此评论");
                }
            }
            
            // 执行删除操作
            int result = commentDao.delete(commentId);
            
            if (result == 0) {
                throw new CommentException("评论不存在或已被删除");
            }
            
            logger.info("评论删除成功");
            return true;
            
        } catch (SQLException e) {
            logger.log(Level.SEVERE, "删除评论时发生数据库异常: " + e.getMessage(), e);
            throw new CommentException("删除评论失败，请稍后重试", e);
        }
    }
    
    /**
     * 校验评论参数
     * @param articleId 文章ID
     * @param userId 用户ID
     * @param content 评论内容
     * @throws CommentException 评论参数异常
     */
    /**
     * 递归加载评论的回复（支持嵌套回复）
     * @param parentId 父评论ID
     * @return 嵌套的回复列表
     * @throws SQLException 数据库异常
     */
    private List<Comment> loadRepliesRecursively(Integer parentId) throws SQLException {
        // 先加载当前层的回复
        List<Comment> replies = commentDao.findRepliesByParentId(parentId);
        
        // 递归加载每个回复的子回复
        for (Comment reply : replies) {
            List<Comment> nestedReplies = loadRepliesRecursively(reply.getId());
            if (!nestedReplies.isEmpty()) {
                reply.setReplies(nestedReplies);
            }
        }
        
        return replies;
    }
    
    private void validateCommentParams(Integer articleId, Integer userId, String content) throws CommentException {
        // 确保所有必需参数都不为null
        if (articleId == null) {
            throw new CommentException("文章ID不能为空");
        }
        if (articleId <= 0) {
            throw new CommentException("无效的文章ID");
        }
        
        if (userId == null) {
            throw new CommentException("用户ID不能为空");
        }
        if (userId <= 0) {
            throw new CommentException("无效的用户ID");
        }
        
        if (content == null || content.trim().isEmpty()) {
            throw new CommentException("评论内容不能为空");
        }
        
        if (content.length() > 1000) {
            throw new CommentException("评论内容不能超过1000字符");
        }
    }
}